<template>
  <el-card>
    <h3>目标管理</h3>
    <el-table :data="targets" stripe v-loading="loading">
      <el-table-column prop="username" label="员工姓名" width="200" />
      <el-table-column prop="description" label="目标" />
      <el-table-column prop="progress" label="完成进度" width="200">
        <template #default="{ row }">
          <el-progress :percentage="row.progress"></el-progress>
        </template>
      </el-table-column>
      <el-table-column prop="deadline" label="截止日期" width="180">
        <template #default="{ row }">
          <span>{{ row.deadline ? new Date(row.deadline).toLocaleDateString() : '未知' }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getTargetList } from '@/api/target.js'
import { getEmployeeInfo } from '@/api/user.js'
import { ElMessage } from 'element-plus'

const users = ref([])
const departmentId = ref(null)
const allTargets = ref([]) // 存放所有目标数据
const loading = ref(false)

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 计算当前页显示的目标数据
const targets = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return allTargets.value.slice(start, end)
})

// 获取本部门的员工信息
const fetchUsers = async () => {
  try {
    const response = await getEmployeeInfo()

    if (response.data.code === 200) {
      users.value = response.data.data.map((user) => ({
        id: user.id,
        name: user.username,
      }))

      if (users.value.length > 0) {
        departmentId.value = response.data.data[0].departmentId
      }
    } else {
      console.error('❌ 获取员工数据失败:', response.data.message)
      ElMessage.error(`获取员工数据失败: ${response.data.message}`)
    }
  } catch (error) {
    console.error('🚨 请求员工数据时出错:', error)
    ElMessage.error('无法获取员工数据，请检查网络或联系管理员')
  }
}

// 获取目标数据
const fetchTargets = async () => {
  loading.value = true
  try {
    if (users.value.length === 0) {
      return
    }

    let tempTargets = []

    // 遍历部门内所有员工，获取每个人的目标
    for (const user of users.value) {
      const response = await getTargetList(user.id)

      if (response.data.code === 200 && response.data.data.length > 0) {
        const userTargets = response.data.data.map((target) => ({
          ...target,
          username: user.name, // 追加员工姓名
        }))

        tempTargets = [...tempTargets, ...userTargets] // 合并目标数据
      }
    }

    // 更新所有目标数据
    allTargets.value = tempTargets
    // 更新分页总数
    pagination.value.total = allTargets.value.length

  } catch (error) {
    console.error('🚨 请求目标数据时出错:', error)
    ElMessage.error('无法获取目标数据，请检查网络或联系管理员')
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  // 如果当前页超出范围，重置到第一页
  const maxPage = Math.ceil(pagination.value.total / pagination.value.pageSize)
  if (pagination.value.currentPage > maxPage) {
    pagination.value.currentPage = 1
  }
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
}

onMounted(async () => {
  await fetchUsers()
  await fetchTargets()
})
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
